import { getAccessToken, getTenantId } from '@/utils/auth'
import type { UploadUserFile, UploadProps, UploadFile, UploadFiles } from 'element-plus'
const FILE_MAX_SIZE = 50 // 文件大小限制

export function useUpload(checkedList: [string[], string[], string[]]) {
  const { t } = useI18n() // 国际化
  const message = useMessage() // 消息弹窗

  const uploadHeaders = ref({
    Authorization: 'Bearer ' + getAccessToken(),
    'tenant-id': getTenantId()
  })
  const UPLOAD_URL = import.meta.env.VITE_FILE_MANAGE_UPLOAD_URL

  const fileList = ref<UploadUserFile[]>([]) // 文件列表

  const isUploading = ref(false)

  const fileAccept = computed(() => {
    return [...checkedList[0], ...checkedList[1], ...checkedList[2]].join(',')
  })

  /** 上传成功 */
  const submitFormSuccess = (val, file, files) => {
    console.log('files',files)
    if (val.code != 200) {
      message.error(val.message || '上传失败，请您重新上传！')
      const index = files.findIndex((item) => (item.uid == file.uid))
      if (index >= 0) {
        files.splice(index, 1)
      }
      return
    }
    file.list = val.data
    isUploading.value = false

    // console.log('val', val)
    // console.log('files', files)
    // console.log('file', file)
    // formData.value.filePath = val.data.url
  }

  /** 文件数超出提示 */
  const handleExceed = (): void => {
    message.error(t('develop.fileMaxNum'))
  }
  /** 上传错误提示 */
  const submitFormError = (): void => {
    message.error('上传失败，请您重新上传！')
    isUploading.value = false
  }
  /** 上传进度 */
  const handleProgress = (evt) => {
    console.log('evt', evt)
  }
  /** 上传前 */
  const handleBefore: UploadProps['beforeUpload'] = (rawFile) => {
    if (rawFile.size / 1024 / 1024 > FILE_MAX_SIZE) {
      message.error('文件大小不能超过50MB')
      return false
    }
    isUploading.value = true
    return true
  }

  /** 移除文件 */

  const handleRemove = (_uploadFile: UploadFile, uploadFiles: UploadFiles) => {
    if (!uploadFiles.some((item) => item.status === 'uploading')) isUploading.value = false
  }

  return {
    uploadHeaders,
    UPLOAD_URL,
    fileList,
    submitFormSuccess,
    handleExceed,
    submitFormError,
    fileAccept,
    handleProgress,
    handleBefore,
    isUploading,
    handleRemove
  }
}
